package com.sz.common.core.system.service.impl;

import com.sz.common.base.service.AbstractService;
import com.sz.common.core.system.entity.ApiCost;
import com.sz.common.core.system.service.ApiCostService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Function: ApiCostServiceImpl. <br>
 * Date: 2017年02月14日 11:18 <br>
 * Author: wentao.chang
 */
@Service
public class ApiCostServiceImpl extends AbstractService implements ApiCostService {
    @Override
    public void saveApiCost(ApiCost apicost) {
        dao.save("ApiCostMapper.insert", apicost);
    }

    @Override
    public void updateApiCost(ApiCost apicost) {
        dao.update("ApiCostMapper.update", apicost);
    }

    @Override
    public ApiCost findByApi(String api) {
        return (ApiCost) dao.findForObject("ApiCostMapper.findByApi", api);
    }

    @Override
    public void handlerCost(String url, float cost) {
        ApiCost apiCost = findByApi(url);
        BigDecimal thisCost = new BigDecimal(cost);
        if (apiCost == null) {
            apiCost = new ApiCost();
            apiCost.setCount(BigDecimal.ONE);
            apiCost.setApi(url);
            apiCost.setMin(thisCost);
            apiCost.setMax(thisCost);
            apiCost.setLast(thisCost);
            apiCost.setLastTimestamp(new Date());
            apiCost.setTotal(thisCost);
            saveApiCost(apiCost);
        } else {

            if (thisCost.compareTo(apiCost.getMin()) < 0) {
                apiCost.setMin(thisCost);
            }
            if (apiCost.getMax().compareTo(thisCost) < 0) {
                apiCost.setMax(thisCost);
            }
            apiCost.setCount(apiCost.getCount().add(BigDecimal.ONE));
            apiCost.setTotal(apiCost.getTotal().add(thisCost));
            apiCost.setLast(thisCost);
            apiCost.setLastTimestamp(new Date());
            updateApiCost(apiCost);
        }
    }

    @Override
    protected String getMapperNamespace() {
        return "";
    }
}
